package com.qb.devserv;

import static com.qb.devserv.MainService.mService;

import static utils.SystemPropertiesReflection.demo;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.Settings;
import android.view.Gravity;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import androidx.annotation.NonNull;
import com.xuexiang.xui.XUI;
import com.xuexiang.xui.utils.WidgetUtils;
import com.xuexiang.xui.widget.dialog.MiniLoadingDialog;
import com.xuexiang.xui.widget.toast.XToast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Date;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
//import pub.devrel.easypermissions.EasyPermissions;
import utils.AppUtil;
import utils.DevActionUtil;
import utils.DevInfoUtil;
import utils.MyUtil;
import utils.SystemPropertiesReflection;

public class MainActivity extends Activity {

    Context ctx;
    public static MainActivity mActivity;
    public SharedPreferences SP;
    MiniLoadingDialog mMiniLoadingDialog;
    String mainFlag;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        MyUtil.serviceGo(this);
        XUI.initTheme(this);
        XToast.Config.get().setGravity(Gravity.CENTER);
        mMiniLoadingDialog = WidgetUtils.getMiniLoadingDialog(this);
        super.onCreate(savedInstanceState);
        //requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        mainFlag = getIntent().getStringExtra("MainFlag");
        ctx = this;
        mActivity = this;
        SP = getSharedPreferences("dev_mgt_setting", this.MODE_PRIVATE);

        Window window = this.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.gravity = Gravity.CENTER;
        lp.width = 650; //WindowManager.LayoutParams.WRAP_CONTENT;
        lp.height = 150; //WindowManager.LayoutParams.MATCH_PARENT;
        this.getWindow().setAttributes(lp);

        hasManageOverlayPermission();

        new Handler().postDelayed(()-> {
            MyUtil.showLog("SystemPropertiesReflection", demo);
            SharedPreferences.Editor edit = SP.edit();
            String board_factory = SystemPropertiesReflection.get("ro.build.user");
            edit.putString("BOARD_FACTORY", board_factory);
            edit.apply();
        },300);

    }

    // 显示绑定界面
    public void init(String flag) {
        if (flag.equals("DEVICE_BIND")) {
            startActivities(new Intent[]{new Intent().setClass(this, FactoryActivity.class)});
        } else {
            autoRunTask();
        }
    }

    // 检查开机自动启动
    public void autoRunTask() {
        String pkName = SP.getString("autorunApp","");
        MyUtil.showLog("autoRunTask",pkName);
        if (!MyUtil.isNull(pkName)) {
            AppUtil.startAppByPackage(ctx,pkName);
        }
    }

    //上传设备明细
    public void upLoadDevDetail() {
        String romId = SystemPropertiesReflection.get("ro.build.display.id");
        JSONArray appList = AppUtil.getAppList(ctx);
        JSONArray paramData = new JSONArray();
        JSONObject o;
        try {
            o = new JSONObject();
            o.put("key","处理器");
            o.put("value",DevInfoUtil.getCpuInfo("Hardware"));
            paramData.put(o);
            o = new JSONObject();
            o.put("key","运行内存(可用/总)");
            String ram = DevInfoUtil.getRAM(ctx).getString("avail")+"/"+DevInfoUtil.getRAM(ctx).getString("total");
            o.put("value",ram);
            paramData.put(o);
            o = new JSONObject();
            o.put("key","存储(可用/总)");
            String rom = DevInfoUtil.getROM(ctx).getString("avail")+"/"+DevInfoUtil.getROM(ctx).getString("total");
            o.put("value",rom);
            paramData.put(o);
            o = new JSONObject();
            o.put("key","Android版本");
            o.put("value",DevInfoUtil.getOsInfo());
            paramData.put(o);
            o = new JSONObject();
            o.put("key","系统版本号");
            o.put("value",romId);
            paramData.put(o);
            JSONArray screenInfo = DevInfoUtil.getScreenInfo(ctx);
            for(int i=0;i<screenInfo.length();i++) {
                o = new JSONObject();
                if (i==0) o.put("key","主屏");
                else if (i==1)  o.put("key","副屏");
                else o.put("key","副屏"+i);
                o.put("value","分辨率"+screenInfo.get(i).toString());
                paramData.put(o);
            }
            JSONArray netType = DevInfoUtil.getNetworkType(ctx);
            for(int i=0;i<netType.length();i++) {
                JSONObject netTYpe_o = new JSONObject(netType.get(i).toString());
                if (!MyUtil.isNull(netTYpe_o)) {
                    o = new JSONObject();
                    o.put("key","网络类型");
                    o.put("value",netTYpe_o.getString("type"));
                    paramData.put(o);
                    o = new JSONObject();
                    o.put("key","MAC地址");
                    o.put("value",netTYpe_o.getString("mac"));
                    paramData.put(o);
                }
            }
            JSONArray localIp = DevInfoUtil.getLocalIP();
            for(int i=0;i<localIp.length();i++) {
                JSONObject localIp_o = new JSONObject(localIp.get(i).toString());
                if (!MyUtil.isNull(localIp_o)) {
                    o = new JSONObject();
                    o.put("key","局域网类型");
                    o.put("value",localIp_o.getString("type"));
                    paramData.put(o);
                    o = new JSONObject();
                    o.put("key","ipv6地址");
                    o.put("value",localIp_o.getString("ipv6"));
                    paramData.put(o);
                    o = new JSONObject();
                    o.put("key","ipv4地址");
                    o.put("value",localIp_o.getString("ipv4"));
                    paramData.put(o);
                }
            }
            JSONObject bleInfo = DevInfoUtil.getBleInfo(ctx);
            String bleName = "unKnown";
            try {
                bleName = bleInfo.getString("name");
            } catch(Exception e){
                e.printStackTrace();
            }
            o = new JSONObject();
            o.put("key","蓝牙名称");
            o.put("value",bleName);
            if (!bleName.equals("unKnown")) paramData.put(o);
            String bleMac = "unKnown";
            try {
                bleMac = bleInfo.getString("mac");
            } catch(Exception e){
                e.printStackTrace();
            }
            o = new JSONObject();
            o.put("key","蓝牙MAC地址");
            o.put("value",bleMac);
            if (!bleMac.equals("unKnown")) paramData.put(o);

            o = new JSONObject();
            o.put("key","参数更新时间");
            o.put("value",MyUtil.formatDateTime(new Date()));

            paramData.put(o);
            JSONObject p = new JSONObject();
            p.put("setups",paramData);
            p.put("installed_apps",appList);
            mService.sendMsg("DEVICE_DETAIL",p);
        } catch (JSONException e) {
            Toast.makeText(ctx, "设备详情上传失败，"+e.getMessage(), Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }

    // 错误提示窗口
    public void showError(String err) {
        Intent intent = new Intent(this, DialogActivity.class);
        intent.putExtra("flag","error");
        intent.putExtra("title","网络错误");
        intent.putExtra("msg",err);
        startActivity(intent);
        finish();
    }

    //获取悬浮窗权限
    public void hasManageOverlayPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(this)) {
            //没有权限，须要申请权限，由于是打开一个受权页面，因此拿不到返回状态的，因此建议是在onResume方法中重新执行一次校验
            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
            intent.setData(Uri.parse("package:" + this.getPackageName()));
            startActivityForResult(intent,1);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            Intent intent = new Intent();
            if (Environment.isExternalStorageManager()) {
                //intent.setAction(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
                finish();
            } else {
                intent.setAction(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                intent.setData(Uri.parse("package:" +this.getPackageName()));
                startActivityForResult(intent, 2);
            }
        } else {
            finish();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        MyUtil.showLog("onActivityResult",requestCode);
        if (requestCode <= 2) {
            hasManageOverlayPermission();
        }
    }

    /*
     * http
     * */
    public void httpAction(String flag,String url,String method,String postJson) {
        String BaseUrl = SP.getString("baseUrl","");
        if (BaseUrl.indexOf(".") < 10) {
            showError("无效的服务器"+BaseUrl);
            return;
        }
        url = BaseUrl+url;
        String token = SP.getString("token","");
        MyUtil.showLog("httpAction",flag);
        MyUtil.showLog("",url);
        MyUtil.showLog("",method);
        MyUtil.showLog("",postJson);
        MyUtil.showLog("token",token);
        if (method.equals("get")) mMiniLoadingDialog.updateMessage("数据加载中…");
        if (method.equals("post")) mMiniLoadingDialog.updateMessage("设置中…");
        //mMiniLoadingDialog.show();
        OkHttpClient ohc = new OkHttpClient();
        Request request = null;
        if (method.equals("get")) {
            request = new Request.Builder().url(url)
                    .addHeader("Authorization", "Bearer "+token)
                    .build();
        }
        if (method.equals("post")) {
            RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), postJson);
            request = new Request.Builder().url(url).post(requestBody)
                    .addHeader("Authorization", "Bearer "+token)
                    .build();
        }
        ohc.newCall(request).enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                MyUtil.showLog("httpAction onFailure",e.getMessage());
                runOnUiThread(() -> {
                    mMiniLoadingDialog.dismiss();
                    //XToastUtils.error("网络连接失败 "+e.getMessage(), Toast.LENGTH_LONG);
                    showError("网络连接失败 "+e.getMessage());
                });
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                successResult(response, flag);
            }
        });
    }
    public void successResult(Response res, String flag) {
        runOnUiThread(() -> {
            mMiniLoadingDialog.dismiss();
        });
        if (res.code() == 200) {
            try {
                String r = "{}";
                try {
                    r = res.body().string();
                    MyUtil.showLog("httpAction success",r);
                } catch (Exception e) {
                    //XToastUtils.error("返回值获取失败 "+e.getMessage(), Toast.LENGTH_LONG);
                    showError("HTTP返回数据获取失败 "+e.getMessage());
                    e.printStackTrace();
                }
                JSONObject rObj = new JSONObject(r);
                String rCode = rObj.get("code").toString();
                String rMsg = rObj.get("msg").toString();
                if (rCode.equals("10000")) {
                    String dStr = rObj.get("data").toString();
                    JSONArray data = new JSONArray(MyUtil.isNull(dStr)?"[]":dStr);
                    runOnUiThread(() -> {
//                        if (flag.equals("login")) appInit(data);
                    });
                } else {
                    runOnUiThread(() -> {
                        //XToastUtils.error(rMsg, Toast.LENGTH_LONG);
                        showError(rMsg);
                    });
                }
            } catch (JSONException e) {
                runOnUiThread(() -> {
                    //XToastUtils.error("查询失败 "+e.getMessage(), Toast.LENGTH_LONG);
                    showError("查询失败 "+e.getMessage());
                });
                e.printStackTrace();
            }
        } else {
            runOnUiThread(() -> {
                //XToastUtils.error("查询失败 "+res.code(), Toast.LENGTH_LONG);
                showError("查询失败 "+res.code());
            });
        }
    }
}